package ccc.hqu.edu.cn.whatmaps;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;

import java.io.IOException;

public class RunActivity extends AppCompatActivity {

    public MapView mMapView = null;
    public BaiduMap mBaiduMap = null;
    public LocationClient mLocationClient = null;
    double[] myloc = new double[2];//我的地址
    public Intent csintent = null; //用于管理后台定位的Service
    CheckService.MyBinder binder;
    FloatingActionButton stop;
    TextView dis_textView;
    boolean isshowdialog = false;
    boolean end = false;
    boolean shouldPlay = true;
    // 保持所启动的Service的IBinder对象
    int dis=0;
    int r;
    MyLocationData locData;
    SharedPreferences preferences;
    private Vibrator vibrator;//震动
    VibrationEffect mvibration = VibrationEffect.createWaveform(new long[]{300,500},0);//设置震动方式
    MediaPlayer mediaPlayer;
    //通知栏功能所需对象
    Notification.Builder builder=null;
    Notification notification = null;
    NotificationChannel channel = null;

    Thread mThread = new Thread(){
        @Override
        public void run(){
            Boolean isfirst = true;
            while (!end){
                try{
                    Thread.sleep(500);//刷新间隔0.5s
                }
                catch (InterruptedException e){}
                dis = binder.getDistase();
                locData = binder.getlocation();
                MapStatusUpdate mMapStatusUpdate;
                mBaiduMap.setMyLocationData(locData);
                if (isfirst && locData!=null) {
                    LatLng latlng = new LatLng(locData.latitude, locData.longitude);
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(latlng)
                            .zoom(20)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.setMapStatus(mMapStatusUpdate);
                    isfirst = false;
                }
                if(dis - r > 0){
                    String text = "距离围栏"+(dis-r)+"米";
                    dis_textView.setText(text);
                }else {
                    String text = "距离围栏外围"+(r-dis)+"米";
                    dis_textView.setText(text);
                }
            }

        }
    };//用于更新位置和距离的进程

    ServiceConnection myServiceConn = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // IBinder service为onBind方法返回的Service实例
            mThread.start();
            binder = (CheckService.MyBinder) service;
            binder.getService().setDataCallback(new CheckService.DataCallback() {
                //执行回调函数
                @Override
                public void OutOfFence() {
                    if(!isshowdialog){
                        isshowdialog = true;
                        end = true;
                        if(preferences.getBoolean("shock",false)){
                            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            vibrator.vibrate(mvibration);
                        }//震动
                        if (preferences.getBoolean("sound",false) && shouldPlay && mediaPlayer != null) {
                            mediaPlayer = initmediaplayer();
                            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                        }//播放提示音
                        final android.app.AlertDialog.Builder normalDialog =
                                new android.app.AlertDialog.Builder(RunActivity.this);
                        normalDialog.setCancelable(false);
                        normalDialog.setIcon(R.drawable.ic_launcher_background);
                        normalDialog.setMessage("您已经出去围栏了！");
                        normalDialog.setPositiveButton("继续检测",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        end = false;
                                        isshowdialog=false;
                                        if(mediaPlayer != null){
                                            mediaPlayer.stop();
                                        }
                                        if(vibrator != null){
                                            vibrator.cancel();
                                        }
                                    }
                                });
                        normalDialog.setNegativeButton("停止检测",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        stopService(csintent);
                                        unbindService(myServiceConn);
                                        RunActivity.this.finish();
                                        isshowdialog=true;
                                        if(mediaPlayer != null){
                                            mediaPlayer.stop();
                                        }
                                        if(vibrator != null){
                                            vibrator.cancel();
                                        }
                                    }
                                });
                        normalDialog.show();
                        // 显示
                    }
                }
                @Override
                public void InOfFence() {
                    if(!isshowdialog)
                    {
                        isshowdialog=true;
                        end = true;
                        if(preferences.getBoolean("shock",false)){
                            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            vibrator.vibrate(mvibration);
                        }//震动
                        if (preferences.getBoolean("sound",false) && shouldPlay && mediaPlayer != null) {
                            mediaPlayer = initmediaplayer();
                            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                        }//播放提示音
                        final android.app.AlertDialog.Builder normalDialog =
                                new android.app.AlertDialog.Builder(RunActivity.this);
                        normalDialog.setCancelable(false);
                        normalDialog.setMessage("您已经进入围栏了！");
                        normalDialog.setPositiveButton("继续检测",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //...To-do
                                        end = false;
                                        isshowdialog=false;
                                        if(mediaPlayer != null){
                                            mediaPlayer.stop();
                                        }
                                        if(vibrator != null){
                                            vibrator.cancel();
                                        }
                                    }
                                });
                        normalDialog.setNegativeButton("停止检测",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        stopService(csintent);
                                        unbindService(myServiceConn);
                                        RunActivity.this.finish();
                                        isshowdialog=true;
                                        if(mediaPlayer != null){
                                            mediaPlayer.stop();
                                        }
                                        if(vibrator != null){
                                            vibrator.cancel();
                                        }
                                    }
                                });
                        // 显示
                        normalDialog.show();
                    }
                }
            });
        }
        // 服务奔溃或者被杀掉执行
        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_run);

        Intent intent = getIntent();
        final double location[] = intent.getDoubleArrayExtra("oploc");//目标坐标接收
        r = intent.getIntExtra("radius",20);//获取半径
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        //提示音相关
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        AudioManager audioService = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            shouldPlay = false;
        }
        mediaPlayer = initmediaplayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);


        //百度地图API相关
        mMapView =findViewById(R.id.bmapView_run);
        mBaiduMap = mMapView.getMap();
        MapView.setMapCustomEnable(true);
        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(this);//声明LocationClient类
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setNeedDeviceDirect(true);
        //设置locationClientOption
        mLocationClient.setLocOption(option);
        mLocationClient.start();

        //下面的代码是用来绘制围栏范围的。
        LatLng locre = new LatLng(location[0],location[1]);
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.marker);
        OverlayOptions option1 = new MarkerOptions()
                .position(locre)
                .perspective(false)
                .icon(bitmap);
        mBaiduMap.addOverlay(option1);

        CircleOptions mCircleOptions = new CircleOptions().center(locre)
                .radius(r)//这边是半径,单位：米
                .fillColor(0x66FF0000) //填充颜色
                .stroke(new Stroke(5, 0xAAff0000)); //边框宽和边框颜色
        //在地图上显示圆
        mBaiduMap.addOverlay(mCircleOptions);

        stop = findViewById(R.id.button_stop);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExitDialog();
            }
        });
        dis_textView = findViewById(R.id.dis_textView);

        //以下代码用于启动服务
        csintent = new Intent(RunActivity.this,CheckService.class);
        csintent.putExtra("op_loc",location);//此处是传输的坐标
        csintent.putExtra("radius",r);//此处是传输的半径
        csintent.putExtra("mode",intent.getIntExtra("state",1));//此处是传输状态
        startService(csintent);
        bindService(csintent,myServiceConn, Service.BIND_AUTO_CREATE);

        isshowdialog = false;

        //下面的代码用于显示通知栏提醒
        channel = new NotificationChannel("channel_whatmap", "whatmap_notification", NotificationManager.IMPORTANCE_DEFAULT);
        builder = new Notification.Builder (RunActivity.this,"channel_whatmap");//获取一个Notification构造器
        Intent nfIntent = new Intent(RunActivity.this.getApplicationContext(), RunActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(RunActivity.this, 0, nfIntent, 0)) // 设置PendingIntent
                .setCategory(Notification.CATEGORY_MESSAGE)
                .setContentTitle("正在进行后台定位") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("后台定位通知") // 设置上下文内容
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        mLocationClient.enableLocInForeground(1001, notification);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mLocationClient.disableLocInForeground(true); //这句用来停止通知
        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        if(mediaPlayer != null){
            mediaPlayer.stop();
        }
        if(vibrator != null){
            vibrator.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed(){
        showExitDialog();
    }

    private void showExitDialog(){
        final AlertDialog.Builder exitDialog =
                new AlertDialog.Builder(RunActivity.this);
        exitDialog.setMessage("您确定要停止继续设置地理围栏吗？");
        exitDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        stopService(csintent);
                        unbindService(myServiceConn);
                        if(mediaPlayer != null){
                            mediaPlayer.stop();
                        }
                        if(vibrator != null){
                            vibrator.cancel();
                        }
                        RunActivity.this.finish();
                    }
                });
        exitDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        // 显示
        exitDialog.show();
    }//显示停止对话框

    private MediaPlayer initmediaplayer(){
        MediaPlayer mediaPlayer = new MediaPlayer();
        AssetFileDescriptor file = selectfile();
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.setVolume(11, 11);
            mediaPlayer.prepare();
        } catch (IOException ioe) {
            Log.w("error", ioe);
            mediaPlayer = null;
        }
        return mediaPlayer;
    }

    private AssetFileDescriptor selectfile(){
        switch (preferences.getString("sound_value","电话声")){
            case "电话声":{
                return RunActivity.this.getResources().openRawResourceFd(
                        R.raw.sound_telephone);
            }
            case "警报声":{
                return RunActivity.this.getResources().openRawResourceFd(
                        R.raw.sound_warning);
            }
            default:{
                return RunActivity.this.getResources().openRawResourceFd(
                        R.raw.sound_telephone);
            }
        }
    }
}
